#! /usr/bin/env python
#coding=utf-8
from fiction.models import Fiction, Chapter
from django.http import HttpResponse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.shortcuts import render_to_response

def test(request):
    fictions = Fiction.objects.all()
    return render_to_response('story.html', {"chapter": fictions})

def show(request, id, page):
    fiction = Fiction.objects.get(id = id)
    chapter_list = fiction.chapter_set.all().order_by('-id')
    paginator = Paginator(chapter_list, 10) # Show 10 contacts per page
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(page)#int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        chapters = paginator.page(page)
    except (EmptyPage, InvalidPage):
        chapters = paginator.page(paginator.num_pages) 
    return render_to_response('list.html', {"chapters": chapters, "fiction": fiction})

#def start(request):
#    import time
#    from fiction.crawler import *
#    bigloop = 0
#    xxx = 1
#    while xxx:
#        bigloop = bigloop + 1
#        print 'start_fiction'
#        print bigloop
#        fiction_list = Fiction.objects.all()
#        for fiction in fiction_list:
#            db_chapter_list_num = Chapter.objects.filter(fiction = fiction).count()
#            chapter_list =qidianchaptercatcher(fiction.url)
#            i = len(chapter_list)
#            if db_chapter_list_num != i:
#                for chapter in chapter_list[db_chapter_list_num:]:
#                    fiction.chapter_set.create(chapter = chapter)
#            print 'one fiction done!'
#            time.sleep(5)
#        
#        print 'start_chapter'
#        smallloop = 100
#        new_chapter_list = Chapter.objects.filter(url = '')
#        print new_chapter_list.count()
#        for chapter in new_chapter_list:
#            smallloop = smallloop + 1
#            print smallloop
#            url = baidufristhrefcatcher(chapter.chapter)
#            chapter.url = url
#            chapter.save()
#            time.sleep(10)
#        time.sleep(600)
#    return 'never done!'